import { getCartData_API, putCardData_API } from "@/api/cart.js";
export default {
  namespaced: true,
  state: {
    cardList: [],
    priceArr: [],
  },
  getters: {
    total(state) {
      return state.cardList.length;
    },
    totalPrices(state) {
      state.cardList.forEach((item) => {
        state.priceArr.push(item.price * item.count);
      });
      const result = state.priceArr.reduce(
        (previous, current) => previous + current,
        0
      );
      state.priceArr = [];
      return result;
    },
  },
  mutations: {
    commodity(state, payload) {
      state.cardList = payload;
    },
  },
  actions: {
    async getCartList({ commit }) {
      const { data } = await getCartData_API();
      commit("commodity", data);
    },

    async putCartList(context, { data: payload, name }) {
      if (name === "add") {
        payload.count++;
      }
      if (name === "reduce") {
        payload.count--;
      }
      const result = await putCardData_API(payload);
    },
  },
};
